const express = require('express');
const app = express();
const axios = require('axios');
const jwt = require('jsonwebtoken'); // 如果需要鉴权
const cors = require('cors');
const port =  3001;
global.secretKey = "shsim";
const apiKey="sk-bqwxsoazofxhpjmprkayshzqpdfbrvgpxlsmvqqbsmexslsf"
const shsServerAllowedOrigins = ['http://ctrlikun.com', 'https://ctrlikun.com',
	'https://www.ctrlikun.com', 'http://www.ctrlikun.com',
	'http://www.ctrlikun.com/', 'http://ctrlikun.com/',
	"shsim.ctrlikun.com", "http://shsim.ctrlikun.com", "https://shsim.ctrlikun.com"
];
shsServerAllowedOrigins.push("http://127.0.0.1:8080", 'http://localhost:8080')
shsServerAllowedOrigins.push("http://192.168.31.78:8080")
// 启用 CORS
app.use(cors({
	origin: function(origin, callback) {
		// 允许预检请求
		if (!origin || shsServerAllowedOrigins.indexOf(origin) !== -1) {
			callback(null, true);
		} else {
			callback(new Error('SHS--Not allowed by CORS'));
		}
	}, // 允许的源
	methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的HTTP请求方法
	allowedHeaders: ['Content-Type', 'Authorization'], // 允许的HTTP请求头
	optionsSuccessStatus: 204 // 成功的HTTP响应状态码
}));

// 解析 JSON 请求体
app.use(express.urlencoded({
	extended: false
}));
app.use(express.json());

// 鉴权中间件（如果需要）
const authenticateToken = (req, res, next) => {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.sendStatus(401);

  jwt.verify(token, secretKey, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
};

// 聊天上下文管理器
let chatContext = []; // 保存聊天上下文
const maxContextLength =  5; // 上下文长度配置

// 向 AI 聊天接口发送请求
async function callAIChatApi(userMessage) {
  try {
    // 向 AI 聊天接口发送请求
    const response = await axios.post(
      'https://api.siliconflow.cn/v1/chat/completions',
      {
        model: "deepseek-ai/DeepSeek-V3",
        messages: [...chatContext, { role: "user", content: userMessage }],
        stream: false,
        max_tokens: 512,
        stop: ["null"],
        temperature: 0.7,
        top_p: 0.7,
        top_k: 50,
        frequency_penalty: 0.5,
        n: 1,
        response_format: { type: "text" },
        tools: [
          {
            type: "function",
            function: {
              description: "<string>",
              name: "<string>",
              parameters: {},
              strict: false
            }
          }
        ]
      },
      {
        headers: {
          Authorization: `Bearer ${apiKey}`, // 替换为你的 API Token
          "Content-Type": "application/json"
        }
      }
    );

    // 提取 AI 回复
    const aiReply = response.data.choices[0].message.content;
    return aiReply;

  } catch (error) {
    console.error('AI 聊天接口请求失败:', error);
    throw new Error('AI 聊天接口请求失败');
  }
}

// 聊天接口
app.post('/api/chat', authenticateToken, async (req, res) => {
  try {
    const { userMessage, contextLength } = req.body;

    // 更新上下文
    chatContext.push({ role: "user", content: userMessage });
    // 控制上下文长度
    if (contextLength && contextLength < chatContext.length) {
      chatContext = chatContext.slice(chatContext.length - contextLength);
    }

    // 调用 AI 聊天接口
    const aiReply = await callAIChatApi(userMessage);

    // 更新上下文
    chatContext.push({ role: "assistant", content: aiReply });

    res.json({
      status: "success",
      message: aiReply,
      context: chatContext // 返回当前上下文
    });

  } catch (error) {
    res.status(500).json({ status: "error", message: error.message });
  }
});

// 启动服务器
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});